package vn.com.bookstore.adapter;

import java.util.ArrayList;

import vn.com.bookstore.Config;
import vn.com.bookstore.R;
import vn.com.bookstore.model.Book;
import vn.com.bookstore.util.lazzyloading.ImageLoader;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CoverAdapter extends BaseAdapter {
	public Context mContext;
	public ArrayList<Book> mDatas = new ArrayList<Book>();

	public CoverAdapter(Context context, ArrayList<Book> data) {
		this.mContext = context;
		this.mDatas = data;
	}
	
	public void setData(ArrayList<Book> lstBook){
		mDatas = new ArrayList<Book>(lstBook);
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return Integer.MAX_VALUE;
//		return mDatas.size();
	}

	@Override
	public Object getItem(int arg0) {
		if(mDatas==null || mDatas.isEmpty()) return 0;
		return mDatas.get(arg0 % mDatas.size());
	}

	@Override
	public long getItemId(int arg0) {
		if(mDatas==null || mDatas.isEmpty()) return 0;
		return arg0 % mDatas.size();
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		View v = arg1;
		if (v == null) {
			v = LayoutInflater.from(mContext)
					.inflate(R.layout.item_cover, null);
			ViewHolder holder = new ViewHolder(v);
			v.setTag(holder);
		}
		ViewHolder holder = (ViewHolder) v.getTag();
		if(mDatas==null || mDatas.isEmpty()) return v;
		holder.setData(mDatas.get(arg0 % mDatas.size()));
		return v;
	}

	class ViewHolder {
		View parent;
		ImageView imv;
		TextView tv;

		public ViewHolder(View parent) {
			this.parent = parent;
			this.imv = (ImageView) parent.findViewById(R.id.iv);
			this.tv = (TextView)parent.findViewById(R.id.textview);
		}

		public void setImage(Bitmap bmp) {
			imv.setImageBitmap(bmp);
		}
		
		public void setData(Book book){
			tv.setText(book.title);
			new ImageLoader(mContext).DisplayImage(Config.getUrlImage(book.image), imv);
		}
	}
}
